package com.qh.physicsexperiment.config;

import com.qh.physicsexperiment.service.UserRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //ShiroFilterFactoryBean:3
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager);//设置安全管理器
        //添加shiro的内置过滤器
        /*
        anon:无需认证就可以访问
        authc:必须认证才能访问
        user:必须拥有 记住我 功能才能用
        perms: 拥有对某个资源的权限才能访问
        roles: 拥有某个角色权限才能访问
         */
        Map<String,String> filterMap = new LinkedHashMap<>();

        filterMap.put("/water/*","authc");
        filterMap.put("/index.html","authc");
        filterMap.put("/show.html","authc");
        filterMap.put("/village","authc");
        //授权 未授权应跳到未授权页面
//        filterMap.put("/user/add.html","perms[user:add]");
//        filterMap.put("/user/update.html","perms[user:update]");
        //拦截
//        filterMap.put("/user/*","authc");
//        bean.setLoginUrl("/toLogin");
        bean.setFilterChainDefinitionMap(filterMap);
        //未授权的页面
//        bean.setUnauthorizedUrl("/noauth");
        //被拦截跳到登录界面
        //设置登录的请求
        bean.setLoginUrl("/tologin");
        return bean;
    }

    @Bean(value = "SecurityManager")  //DefaultWebSecurityManager:2
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager SecurityManager  = new DefaultWebSecurityManager();
        //关联userRealm
        SecurityManager.setRealm(userRealm);
        SecurityManager.setSessionManager(sessionManager());
        return SecurityManager;
    }

    @Bean
    public UserRealm userRealm(){//创建realm对象，需要自定义：1
        return new UserRealm();
    }

    //    https://blog.csdn.net/cristianoxm/article/details/111999168
    @Bean
    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        // 去掉shiro登录时url里的JSESSIONID
        sessionManager.setSessionIdUrlRewritingEnabled(false);
        return sessionManager;
    }

}
